from config.ServerApp import app
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from jobs.ImageProcessJob import process_img_classfy
from config.LoadConfig import get_config
from utils.JobWatchDog import JobWatchDog, Pool, DeviceChecker

job_config = get_config('jobConf')
__max_job_instance = int(job_config.get('max_job_instance', 10))
__execute_interval = int(job_config.get('execute_interval', 10))
system_conf = get_config("system")
# 创建 APScheduler 实例
scheduler = AsyncIOScheduler()
scheduler.configure(timezone='Asia/Shanghai')

scheduler.add_job(process_img_classfy,'interval', seconds=__execute_interval, misfire_grace_time=60,max_instances=5)


class JobManagerConfig:

    # 判断有没有gpu
    device: str = DeviceChecker.get_runtime_env_device()
    # CPU使用率阈值
    __cpu_availability_limit = 30.0 if "cpu_availability_limit" not in system_conf else float(system_conf["cpu_availability_limit"])
    # 内存阈值
    __memory_limit = 2000.0 if "memory_limit" not in system_conf else float(system_conf["memory_limit"])
    # GPU使用率阈值
    __gpu_availability_limit = 10.0 if "gpu_availability_limit" not in system_conf else float(system_conf["gpu_availability_limit"])
    # GPU内存使用阈值
    __gpu_memory_limit = 800.0 if "gpu_memory_limit" not in system_conf else float(system_conf["gpu_memory_limit"])
    # 最低可用线程数
    __min_available_threads_num = 1 if "min_available_threads_num" not in system_conf else int(system_conf["min_available_threads_num"])
    # 最大任务实例数
    max_job_instance = int(job_config.get('max_job_instance', 10))

    @classmethod
    def build_job_watch_dog(cls):
        return JobWatchDog(cls.device, cls.__cpu_availability_limit, cls.__memory_limit, cls.__gpu_availability_limit,
                           cls.__gpu_memory_limit, cls.__min_available_threads_num)


class JobManager:
    pool = Pool(max_threads=JobManagerConfig.max_job_instance, watch_dog=JobManagerConfig.build_job_watch_dog())



@app.listener('before_server_start')
async def setup_scheduler(app, loop):
    scheduler.start()

@app.listener('after_server_stop')
async def shutdown_scheduler(app, loop):
    scheduler.shutdown()

